package com.xunfang.demo.servlet3;

import com.alibaba.fastjson.JSONObject;
import com.xunfang.demo.entity.Education;
import com.xunfang.demo.entity.QueryData;
import com.xunfang.demo.entity.UserDemo;
import com.xunfang.demo.service.EducationService;
import com.xunfang.demo.service.EducationServiceImpl;
import com.xunfang.demo.service.UserService;
import com.xunfang.demo.service.UserServiceImpl;
import com.xunfang.demo.utils.PageBean;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet(name = "MainServlet", urlPatterns = "/main")
public class MainServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();
    EducationService ed = new EducationServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String cmd = request.getParameter("cmd");
        if (cmd != null && cmd.equals("main")) {
            main(request, response);
        } else if (cmd != null && cmd.equals("login")) {
            login(request, response);
        } else if (cmd != null && cmd.equals("DelSession")) {
            DelSession(request, response);
        } else if (cmd != null && cmd.equals("register")) {
            register(request, response);
        } else if (cmd != null && cmd.equals("del")) {
            del(request, response);
        } else if (cmd != null && cmd.equals("update")) {
            update(request, response);
        } else if (cmd != null && cmd.equals("update2")) {
            update2(request, response);
        } else if (cmd != null && cmd.equals("loginUI")) {
            loginUI(request, response);
        }else if (cmd != null && cmd.equals("existsUserName")) {
            existsUserName(request, response);
        }

    }

    public void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = (String) request.getSession().getAttribute("username");
        if (userName == null) {
            //response.getWriter().write("<h1>请登录后在进行操作，5秒之后，跳转到登录页面！</h1>");
            //refresh: 响应头，表示多少秒之后，跳转到指定的url
            response.setHeader("refresh", "5;url=" + request.getContextPath() + "/page/login.jsp");
            return;
        }
        System.out.println("成功登录！！！");

        //获取表单所有的值
        Map<String, String[]> map = request.getParameterMap();
        //创建条件对象
        QueryData queryData = new QueryData();
        //用beanUtil把获取到的值存入实体类中
        try {
            BeanUtils.populate(queryData, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //获取前端传递的第几页
        String StrP = request.getParameter("p");
        //初始化创建第几页
        Integer p = 1;
        if (StrP != null && !StrP.isEmpty()) {
            p = Integer.valueOf(StrP);
        }

        //调
        //问题： 如何把从数据库中查询出来的用户数据，显示到页面上？ 就需要返回创建的PageBean对象，该对象封装了需要显示的所有数据
        PageBean pb = userService.getUserByPB(queryData,p);

        //存
        //注意：如果想在main.jsp中显示数据，那么必须要把list放到【域对象】中，传递到main.jsp中。
        request.setAttribute("pb", pb);
        //把收到的查询保存在页面，查询后依然在,只接使用实体对象放到域对象中
        request.setAttribute("queryData", queryData);

        //转
        //请求转发数据到main.jsp
        request.getRequestDispatcher("/page/main.jsp").forward(request, response);
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收请求数据
        String username = request.getParameter("username");
        String userpwd = request.getParameter("userpwd");
        //判断验证码正确
        //获取用户输入的验证码
        String loginCode = request.getParameter("loginCode");
        //获取session中的验证码，判断是否正确
        String vsCode = (String) request.getSession(false).getAttribute("vsCode");
        if (vsCode == null) {
            request.setAttribute("msg", "服务端验证码获取错误！");
            request.getRequestDispatcher("/page/index.jsp").forward(request, response);
            //验证失败，不执行下面代码
            return;
        }
        if (!loginCode.equalsIgnoreCase(vsCode)) {
            request.setAttribute("msg", "验证码错误!");
            request.getRequestDispatcher("/page/index.jsp").forward(request, response);
            //验证失败，不执行下面代码
            return;
        }
        //2.处理数据-调用业务层的方法
        boolean bool = userService.existsUsers(username, userpwd);
        //3.响应结果
        if (bool) {
            request.getSession().setAttribute("username", username);
            //转发和重定向都可以 - 登录成功，转发到主页面
            main(request, response);
            //request.getRequestDispatcher("/main?cmd=main").forward(request, response);
        } else {
            //登录失败，回到登录页面
            response.sendRedirect(request.getContextPath() + "/page/index.jsp?msg=error");
        }
    }

    public void DelSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            //移除session用户
            session.removeAttribute("username");
            //重定向
            response.sendRedirect(request.getContextPath() + "/page/index.jsp");
        } else {
            response.sendRedirect(request.getContextPath() + "/page/index.jsp");
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取指定的请求参数
        String userName = request.getParameter("userName");
        System.out.println("userName = " + userName);
        //2.获取参数中的一键多值
        String[] chks = request.getParameterValues("chk");
        System.out.println("chks = " + Arrays.toString(chks));
        //3.获取提交的所有参数
        Map<String, String[]> maps = request.getParameterMap();
        UserDemo userDemo = new UserDemo();
        //从前端传递的日期是String格式，但是实体中是Date类型，不能直接转换
        //使用日期转换器，来转换日期格式
        DateConverter dc = new DateConverter();
        //设置转换格式
        dc.setPatterns(new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});
        //实现注册转换
        ConvertUtils.register(dc, Date.class);
        //populate:可以直接把map中的数据赋值给实体类的属性！！！
        //注意：表单中的name属性的名字必须要跟实体中的属性的名字完全一致！！！
        try {
            BeanUtils.populate(userDemo, maps);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //爱好单独处理
        userDemo.setChk(Arrays.toString(chks));
        System.out.println(userDemo);
        //调用业务层方法
        boolean bool = userService.addUser(userDemo);
        if (bool) {
            response.getWriter().write("<h1>恭喜你，注册成功！5秒之后，跳转到登录页面！</h1>");
            //refresh: 响应头，表示多少秒之后，跳转到指定的url
            response.setHeader("refresh", "5;url=" + request.getContextPath() + "/page/index.jsp");
        } else {
            response.sendRedirect(request.getContextPath() + "/page/error.jsp");
        }
    }

    public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //如何接收get请求传递的数据？
        String id = request.getParameter("id");
        boolean bool = userService.removeUserById(Integer.valueOf(id));
        if (bool) {
            request.setAttribute("result", "ok");
        } else {
            request.setAttribute("result", "no");
        }
        //重定向到MainServlet，再次查询用户列表
        main(request, response);
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //取  调  存  转
        //取 - 前端传递的数据
        String id = request.getParameter("id");
        //调 - 调取业务层
        UserDemo userDemo = userService.findUserById(Integer.valueOf(id));
        //存 - 存到域对象
        request.setAttribute("userDemo", userDemo);
        //转 - 转发到页面
        request.getRequestDispatcher("/page/update.jsp").forward(request, response);
    }

    public void update2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] chks = request.getParameterValues("chk");
        System.out.println("chks = " + Arrays.toString(chks));
        //3.获取提交的所有参数
        Map<String, String[]> maps = request.getParameterMap();
        UserDemo userDemo = new UserDemo();
        //从前端传递的日期是String格式，但是实体中是Date类型，不能直接转换
        //使用日期转换器，来转换日期格式
        DateConverter dc = new DateConverter();
        //设置转换格式
        dc.setPatterns(new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"});
        //实现注册转换
        ConvertUtils.register(dc, Date.class);
        //populate:可以直接把map中的数据赋值给实体类的属性！！！
        //注意：表单中的name属性的名字必须要跟实体中的属性的名字完全一致！！！
        try {
            BeanUtils.populate(userDemo, maps);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //爱好单独处理
        userDemo.setChk(Arrays.toString(chks));
        //调用业务层
        boolean b = userService.updateById(userDemo);
        if (b) {
            //response.getWriter().write("<h1>修改成功！5秒之后，跳转到登录页面！</h1>");
            //refresh: 响应头，表示多少秒之后，跳转到指定的url
            //response.setHeader("refresh","5;url="+request.getContextPath()+"/page/main.jsp");
            request.setAttribute("update", "ok");
        } else {
            //response.sendRedirect(request.getContextPath()+"/page/error.jsp");
            request.setAttribute("update", "ok");
        }
        main(request, response);
    }

    public void loginUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //下拉框的数据读取操作
        List<Education> all = ed.findAll();
        request.getSession().setAttribute("educationList", all);
        response.sendRedirect(request.getContextPath() + "/page/index.jsp");
    }

    public void existsUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String userName = request.getParameter("userName");
        System.out.println(userName);
        boolean b = userService.findUserName(userName);
        JSONObject jsonObject = new JSONObject();
        if(b){
            jsonObject.put("msg","no");
            //response.getWriter().write("{\"msg\":\"no\"}");
        }else {
            jsonObject.put("msg","ok");
            //response.getWriter().write("{\"msg\":\"ok\"}");
        }
        //json包只是帮我们创建好json格式，我们还需要自己手动响应过去
        response.getWriter().write(jsonObject.toJSONString());
    }

}
